package com.ruoyi.web.admin.data.utils;

import com.ruoyi.common.utils.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author 10100
 * @license (C) Copyright 2020-2050,  Corporation Limited.
 * @contact 10100
 * @date 2025-06-09 09:10
 * @description 加解密
 */
public class AESUtils {


    // AES-128密钥（16字节 = 128位）
    static byte[] key = new byte[]{(byte) 0x96, (byte) 0xB6, (byte) 0x71, 0x5E, (byte) 0xF5, 0x0F, (byte) 0xA4, (byte) 0x55, 0x7F, 0x6C, (byte) 0xF9, 0x77, 0x17, (byte) 0x8E, (byte) 0x86, (byte) 0xC9};

    // AES初始向量（IV,16字节）
    static byte[] iv = new byte[]{0x11, (byte) 0xC5, 0x00, 0x74, 0x0B, (byte) 0XE4, 0x4D, 0x4E, (byte) 0xE5, (byte) 0xBD, (byte) 0xAE, (byte) 0xD0, 0x3C, (byte) 0xE7, 0x6F, (byte) 0xFF};

    static String suffix = "#kdsjafjalsdjg#170";

    public static String encrypt(String plaintext) {
        if (StringUtils.isEmpty(plaintext)) {
            return null;
        }

        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);

            byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));

            // 对加密后的字节数组进行 Base64 编码
            String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes).replaceAll("\\n", "");

            return encryptedText + suffix;
        } catch (Exception e) {
            return null;
        }
    }

    public static String decrypt(String encryptedBase64) {
        if (encryptedBase64.endsWith(suffix)) {
            encryptedBase64 = encryptedBase64.substring(0, encryptedBase64.length() - suffix.length());
        }

        try {
            byte[] encrypted = Base64.getDecoder().decode(encryptedBase64.replaceAll("\\\\n", ""));
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv);
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] original = cipher.doFinal(encrypted);
            return new String(original, StandardCharsets.UTF_8);
        } catch (Exception e) {
            return null;
        }

    }

    public static void main(String[] args) {
        System.out.println(decrypt("CwQwKF6noAcg0AlX0ZklVpSjqn5M6cI9H9ULoZrBidrPfvX3Am/gYh0AhUNOzqgX5WQZjR5xDABVvvm9g3nxpdsLYLIIVagU2KhwAUdHuyWFT3s/YH+9wSY7SCi1AFu5D7jCNWPSsEvISB3ylwBT32jJF4C/U0B6f+gKxEz6/s8=#kdsjafjalsdjg#170"));
    }
}